﻿using Basic.FlowDAL;
using Basic.FlowModel.DB;
using Basic.FlowModel.NodeRoute;
using Basic.FlowRemoteModel.NodeRoute.Model;
using WeDonekRpc.Helper;

namespace Basic.FlowCollect.lmpl
{
    internal class NodeRouteCollect : INodeRouteCollect
    {
        private readonly IFlowNodeRouteDAL _BasicDAL;

        public NodeRouteCollect ( IFlowNodeRouteDAL basicDAL )
        {
            this._BasicDAL = basicDAL;
        }
        public DBFlowNodeRoute Get ( long id )
        {
            return this._BasicDAL.Get(id);
        }
        public long Add ( RouteAdd data )
        {
            if ( this._BasicDAL.IsExists(c => c.NodeId == data.NodeId && c.ToNodeId == data.ToNodeId) )
            {
                throw new ErrorException("flow.node.route.repeat");
            }
            if ( this._BasicDAL.IsExists(c => c.NodeId == data.ToNodeId && c.ToNodeId == data.NodeId) )
            {
                throw new ErrorException("flow.node.route.repeat");
            }
            return this._BasicDAL.Add(data);
        }
        public void Clear ( long flowId )
        {
            long[] ids = this._BasicDAL.Gets(a => a.FlowId == flowId, a => a.Id);
            if ( !ids.IsNull() )
            {
                this._BasicDAL.Delete(ids);
            }
        }
        public void Clear ( long flowId, long nodeId )
        {
            long formId = this._BasicDAL.Get(a => a.FlowId == flowId && a.NodeId == nodeId, a => a.Id);
            long toId = this._BasicDAL.Get(a => a.FlowId == flowId && a.ToNodeId == nodeId, a => a.Id);
            if ( toId != 0 && formId != 0 )
            {
                this._BasicDAL.Delete(new long[] { formId, toId });
            }
            else if ( toId != 0 )
            {
                this._BasicDAL.Delete(toId);
            }
            else if ( formId != 0 )
            {
                this._BasicDAL.Delete(formId);
            }
        }
        public Result[] Gets<Result> ( long flowId ) where Result : class, new()
        {
            return this._BasicDAL.Gets<Result>(a => a.FlowId == flowId);
        }

        public void Delete ( DBFlowNodeRoute db )
        {
            this._BasicDAL.Delete(db.Id);
        }

        public FromToNode[] GetsFromToNode ( long nodeId )
        {
            return this._BasicDAL.GetsFromToNode(nodeId);
        }

    }
}
